package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"runtime"
	"time"
)

var (
	dnsResolverIP        = "114.114.114.114:53" // Google DNS resolver.
	dnsResolverProto     = "udp"                // Protocol to use for the DNS resolver
	dnsResolverTimeoutMs = 5000                 // Timeout (ms) for the DNS resolver (optional)
)

func main() {

	client := getHttpClient()

	resp, err := client.Get("http://baidu.com/")
	if err != nil {
		fmt.Printf("error is :" + err.Error())
		panic(1)
	}
	defer resp.Body.Close()
	fmt.Printf("%+v \n", resp.Status)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("error is :" + err.Error())
		panic(1)
	}
	fmt.Println(string(body) + "完成")
}

// 获取 httpclient
// golang 中默认使用系统配置 /etc/resolv.conf 文件解析
// 由于 arm 架构中没有此文件,所以需要指定使用的 dns 服务器
// 以下代码: 如果是 arm 架构使用配置 http 的 client
// 如果是非 arm 架构的使用默认的 http client
func getHttpClient() *http.Client {
	if runtime.GOARCH != "arm" {
		return http.DefaultClient
	}

	dialer := &net.Dialer{
		Resolver: &net.Resolver{
			PreferGo: true,
			Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
				d := &net.Dialer{Timeout: time.Duration(dnsResolverTimeoutMs) * time.Millisecond}
				return d.DialContext(ctx, dnsResolverProto, dnsResolverIP)
			},
		},
	}

	dialContext := func(ctx context.Context, network, addr string) (net.Conn, error) {
		return dialer.DialContext(ctx, network, addr)
	}

	http.DefaultTransport.(*http.Transport).DialContext = dialContext
	httpclient := &http.Client{}

	return httpclient
}
